<template>
  <div @click="handleShow">
    <slot name="uploadLink">
      <el-button :icon="Upload" type="primary">导入图片</el-button>
    </slot>
  </div>
  <el-dialog
    v-model="dialogFormVisible"
    :before-close="handleClose"
    :close-on-click-modal="true"
    :draggable="draggable"
    :title="title"
    width="909px"
  >
    <!--    <el-scrollbar>-->
    <div class="upload">
      <el-alert :closable="false" :title="tips" type="info" />
      <el-upload
        ref="uploadRef"
        :accept="accept"
        :action="action"
        :auto-upload="false"
        class="upload-content"
        :close-on-click-modal="false"
        :data="data"
        :file-list="fileList"
        :limit="limit"
        list-type="picture-card"
        :multiple="true"
        :name="name"
        :on-change="handleChange"
        :on-error="handleError"
        :on-exceed="handleExceed"
        :on-preview="handlePreview"
        :on-progress="handleProgress"
        :on-remove="handleRemove"
        :on-success="handleSuccess"
      >
        <template #trigger>
          <vab-icon icon="add-line" />
        </template>
        <el-dialog v-model="dialogVisible" append-to-body title="查看大图">
          <div>
            <el-image :src="dialogImageUrl" />
          </div>
        </el-dialog>
      </el-upload>
    </div>
    <template #footer>
      <div v-if="show" style="position: absolute; top: 10px; left: 15px; color: #999999">
        正在上传中... 当前上传成功数:{{ imgSuccessNum }}张 当前上传失败数:{{ imgErrorNum }}张
      </div>
      <el-button :loading="loading" style="margin-left: 10px" type="success" @click="submitUpload"> 开始上传 </el-button>
      <el-button type="info" @click="handleClose">关闭</el-button>
    </template>
    <!--    </el-scrollbar>-->
  </el-dialog>
</template>

<script>
import _ from "lodash";
import { ElLoading } from "element-plus";
import { uploadUrl } from "@/api/mains";

export default defineComponent({
  name: "UploadImgDialog",
  props: {
    url: {
      type: String,
      default: "/upload",
      required: true
    },
    name: {
      type: String,
      default: "file",
      required: false
    },
    limit: {
      type: Number,
      default: 50,
      required: true
    },
    accept: {
      type: String,
      default: "image/png, image/jpeg"
    },
    tips: {
      type: String,
      default: ""
    },
    size: {
      type: Number,
      default: 1024,
      required: true
    }
  },
  emits: {
    callbackupload: null
  },
  setup(props, { emit }) {
    const { proxy } = getCurrentInstance();
    const $baseMessage = inject("$baseMessage");
    const state = reactive({
      uploadRef: null,
      name: "UploadImgDialog",
      show: false,
      loading: false,
      dialogVisible: false,
      dialogImageUrl: "",
      draggable: true,
      action: "",
      fileList: [],
      picture: "picture",
      imgNum: 0,
      imgSuccessNum: 0,
      imgErrorNum: 0,
      typeList: null,
      title: "上传",
      dialogFormVisible: false,
      accept: "image/png, image/jpeg",
      limit: "5",
      url: "",
      tips: "",
      data: {}
    });

    state.accept = ref(props.accept);
    state.url = ref(props.url);
    state.limit = ref(props.limit);
    state.tips = ref(props.tips);
    state.size = ref(props.size);

    const submitUpload = async () => {
      //state.uploadRef.submit()
      state.loading = true;
      if (state.fileList.length === 0) {
        proxy.$baseMessage("请选取文件", "warning");
        state.loading = false;
        return;
      } else {
        const loading = ElLoading.service({
          lock: true,
          text: "导入中，请稍候...",
          background: "rgba(0, 0, 0, 0.7)"
        });
        const formdata = new FormData();
        state.fileList.forEach(file => {
          formdata.append("upfile", file.raw);
        });
        const responseData = await uploadUrl(props.url, formdata);
        if (responseData.code == 200) {
          proxy.$baseMessage(responseData.msg, "success", false, "vab-hey-message-success");
        } else {
          proxy.$baseMessage(responseData.msg, "error", false, "vab-hey-message-error");
        }
        state.fileList = [];
        emit("callbackupload", responseData);
        handleClose();
        state.loading = false;
        loading.close();
      }
    };
    const handleProgress = () => {
      state.loading = true;
      state.show = true;
    };

    const handleChange = file => {
      if (file.size > state.size) {
        proxy.$baseMessage(`文件大于${state.size}B`, "warning");
        //state['uploadRef'].uploadFiles.splice(0, 1)
        state["uploadRef"].handleRemove(file);
        return false;
      } else {
        state.fileList.push(file);
        return true;
      }
    };

    const handleSuccess = (response, file, fileList) => {
      state.imgNum = state.imgNum + 1;
      state.imgSuccessNum = state.imgSuccessNum + 1;
      if (fileList.length === state.imgNum) {
        setTimeout(() => {
          $baseMessage(`上传完成! 共上传${fileList.length}张图片`, "success", "vab-hey-message-success");
        }, 1000);
      }

      setTimeout(() => {
        state.loading = false;
        state.show = false;
      }, 1000);
    };
    const handleError = (err, file) => {
      state.imgNum = state.imgNum + 1;
      state.imgErrorNum = state.imgErrorNum + 1;
      $baseMessage(
        `文件[${file.raw.name}]上传失败,文件大小为${_.round(file.raw.size / 1024, 0)}KB`,
        "error",
        "vab-hey-message-error"
      );
      setTimeout(() => {
        state.loading = false;
        state.show = false;
      }, 1000);
    };
    const handleRemove = () => {
      state.imgNum = state.imgNum - 1;
      state.allNum = state.allNum - 1;
    };
    const handlePreview = file => {
      state.dialogImageUrl = file.url;
      state.dialogVisible = true;
    };
    const handleExceed = files => {
      $baseMessage(
        `当前限制选择 ${state.limit} 个文件，本次选择了
                  ${files.length}
                  个文件`,
        "error",
        "vab-hey-message-error"
      );
    };
    const handleShow = () => {
      state.title = "上传";
      state.dialogFormVisible = true;
    };
    const handleClose = () => {
      state.fileList = [];
      state.picture = "picture";
      state.allImgNum = 0;
      state.imgNum = 0;
      state.imgSuccessNum = 0;
      state.imgErrorNum = 0;
      state.dialogFormVisible = false;
    };

    onMounted(() => {
      state.action = props.url;
    });

    const percentage = computed(() => {
      if (state.allImgNum === 0) return 0;
      return _.round(state.imgNum / state.allImgNum, 2) * 100;
    });

    return {
      ...toRefs(state),
      submitUpload,
      handleProgress,
      handleChange,
      handleSuccess,
      handleError,
      handleRemove,
      handlePreview,
      handleExceed,
      handleShow,
      handleClose,
      percentage
    };
  }
});
</script>

<style lang="scss" scoped>
.upload {
  .upload-content {
    .el-upload__tip {
      display: block;
      height: 30px;
      line-height: 30px;
    }
    :deep() {
      .el-upload--picture-card {
        width: 128px;
        height: 128px;
        margin: 3px 8px 8px;
        border: 2px dashed #c0ccda;
        .ri-add-line {
          font-size: 24px;
        }
      }
      .el-upload-list--picture {
        margin-bottom: 20px;
      }
      .el-upload-list--picture-card {
        .el-upload-list__item {
          width: 128px;
          height: 128px;
          margin: 3px 8px 8px;
        }
      }
    }
  }
}
</style>
